import java.util.*;

/**
 * @ClassName LC107
 * @Author ykx
 * @Date 2024/3/24 22:29
 * @Version 1.0
 */
public class LC107 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> nums = new ArrayList<>();
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                if (cur == null) {
                    break;
                }
                nums.add(cur.val);
                // 将左孩子入队
                if (cur.left != null) {
                    queue.add(cur.left);
                }
                // 将右孩子入队
                if (cur.right != null) {
                    queue.add(cur.right);
                }
            }
            result.add(nums);
        }
        Collections.reverse(result);
        return result;
    }
}
